import org.apache.commons.lang3.StringUtils;

import java.io.*;

public class FileUtil {

    private static byte[] b = new byte[1024];

    public static void writeString2File(String path, String txt) {
        writeString2File(new File(path), txt);
    }

    public static void writeString2File(File file, String txt) {
        file.getParentFile().mkdirs();
        FileWriter fw = null;
        try {
            fw = new FileWriter(file.getAbsoluteFile());
            fw.write(txt);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(fw);
        }
    }

    public static byte[] file2Bytes(File file) {
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            return input2byte(is);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            close(is);
        }
    }

    public static final byte[] input2byte(InputStream inStream) {
        ByteArrayOutputStream bos = null;
        int n;
        try {
            bos = new ByteArrayOutputStream();
            while ((n = inStream.read(b)) > 0) {
                bos.write(b, 0, n);
            }
            byte[] in2b = bos.toByteArray();
            return in2b;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            close(bos);
        }
    }

    public static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String writeFile(String filePath, String fileName, InputStream inputStream) {
        FileOutputStream fos = null;
        try {
            mkdirs(filePath);
            File file = new File(filePath, fileName);
            fos = new FileOutputStream(file);
            /**
             * 根据实际运行效果 设置缓冲区大小
             */
            int ch;
            while ((ch = inputStream.read(b)) != -1) {
                fos.write(b, 0, ch);
            }
            return file.getAbsolutePath();
        } catch (IOException e) {
            return null;
        } finally {
            close(fos);
            close(inputStream);
        }
    }

    public static boolean mkdirs(String path) {
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return file.mkdirs();
    }
}
